package com.ty.user.starter.controller;

import com.ty.user.starter.annon.Decrypt;
import com.ty.user.starter.annon.Encrypt;
import com.ty.user.starter.annon.TyLog;
import com.ty.user.starter.entity.dto.UserLoginDto;
import com.ty.user.starter.entity.vo.UserVo;
import com.ty.user.starter.enums.LogTypeEnum;
import com.ty.user.starter.exception.UserMgtException;
import com.ty.user.starter.service.UserService;
import com.ty.user.starter.util.R;
import com.ty.user.starter.util.RSAUtil;
import com.ty.user.starter.util.ResponseUtil;
import com.ty.user.starter.util.SessionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.security.KeyPair;

@Api(tags = {"登录相关"})
@RestController
@RequestMapping("mgt/shiro")
public class ShiroController {

    private final UserService userService;

    @Autowired
    public ShiroController(UserService userService) {
        this.userService = userService;
    }

    @TyLog(module = "安全认证", typeEnum = LogTypeEnum.LOGIN, description = "登录")
    @ApiOperation("登录")
    @PostMapping("login")
    public R<UserVo> login( @Valid @RequestBody @Decrypt(field = "password") UserLoginDto dto) {
        return ResponseUtil.success(userService.login(dto));
    }

    @TyLog(module = "安全认证", typeEnum = LogTypeEnum.EXIT, description = "登出")
    @ApiOperation("登出")
    @PostMapping("exit")
    public R<String> exit() {
        SecurityUtils.getSubject().logout();
        return ResponseUtil.success();
    }

    @TyLog(module = "安全认证", typeEnum = LogTypeEnum.OTHER, description = "获取公钥")
    @ApiOperation("获取公钥")
    @GetMapping("public-key")
    public R<String> getPublicKey(HttpSession session) throws UserMgtException {
        KeyPair keyPair = RSAUtil.generateRSAKey();
        session.setAttribute(SessionUtils.RSA_KEY, keyPair);
        return ResponseUtil.success(RSAUtil.encodeBase64(keyPair.getPublic().getEncoded()));
    }

    @ApiOperation("加密演示")
    @Encrypt(field = "password")
    @GetMapping("encrypt")
    public R<UserLoginDto> encrypt() {
        UserLoginDto dto = new UserLoginDto();
        dto.setUsername("liuxiaomin");
        dto.setPassword("12345678");
        return ResponseUtil.success(dto);
    }

}
